package com.sbp.messsage_producer_demo.service.bs;

import com.sbp.message.api.entity.Message;
import com.sbp.message.api.service.MessageService;
import com.sbp.message.api.service.MessageStatusAckService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class TestTopicConsumerServiceImpl implements TestTopicConsumerInterface {
    static final Logger logger = LoggerFactory.getLogger(TestTopicConsumerServiceImpl.class);


    @Autowired
    private MessageService messageService;
    @Autowired
    private MessageStatusAckService messageStatusAckService;


    /****
     * 透传发送消息到broker
     */
    @Override
    public void testTransparentMessage(String content) {
        messageService.createAndSendTransparentMessage(new Message("message-consumer-demo.xxx.yyy", content));
    }

    /****
     * 首先持久化消息到数据库
     * 然后发送消息，修改持久化消息状态
     */
    @Override
    public void testQueueMessage(String content) {
        Message message = messageService.createMessage(new Message("message-consumer-demo.xxx.yyy", content));

        // 执行业务逻辑相关 TODO ...............

        messageStatusAckService.insertAcknowledge(message);
        messageService.confirmAndSendMessage(message);
    }

    @Override
    public void testQueueMessages(int count) {
        List<Message> list = new ArrayList<>();
        for (int i=0; i<count; ++i) {
            Message message = messageService.createMessage(new Message("message-consumer-demo.xxx.yyy", "message index " + i));
            messageStatusAckService.insertAcknowledge(message);

            list.add(message);
        }

        messageService.confirmAndSendMessages(list);
    }


    @Override
    public void testTopicMessage(String content) {
        Message message = messageService.createMessage(Message.generateTopicMessage("xxx", content));

        // 执行业务逻辑相关 TODO ...............

        messageStatusAckService.insertAcknowledge(message);
        messageService.confirmAndSendMessage(message);
    }

}
